package com.ilearn.spring.future.controller;

import com.ilearn.spring.future.dto.AsyncHttpEvent;
import com.ilearn.spring.future.dto.IEvent;
import com.ilearn.spring.future.entity.User;
import com.ilearn.spring.future.service.UserService;
import com.ilearn.spring.future.util.UniqRequestIdGen;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.CompletableFuture;

/**
 * @Project: cmcchq
 * @Description:
 * @Version 1.0
 * @Throws :
 * @Author: <li>2019/6/26 lyndon Create 1.0
 * @Copyright (c)2019-2019 版权所有
 * @Modified By:
 */

@Slf4j
//@RestController
public class FirstFutureController {

    @Autowired
    public UserService userService;


    @GetMapping("/user")
    public CompletableFuture<ResponseEntity<User>> getUser() {

        String threadName = Thread.currentThread().getName();
        String requestId = UniqRequestIdGen.resolveReqId();
        log.info("Thread Name:{}", threadName);
        log.info("Request id: {}", requestId);

        CompletableFuture<User> future = new CompletableFuture<>();
        future.complete(userService.getUser(1, threadName, requestId));
        log.info("Thread {} complete! ReqId is {}", threadName, requestId);

        return future.thenApply(result -> new ResponseEntity<User>(result, HttpStatus.OK));
    }

    @GetMapping("/user1")
    public void process(HttpServletRequest req, HttpServletResponse resp) {
        String threadName = Thread.currentThread().getName();
        String requestId = UniqRequestIdGen.resolveReqId();
        log.info("Thread Name:{}", threadName);
        log.info("Request id: {}", requestId);

        AsyncContext asyncContext = req.startAsync();
        IEvent iEvent = AsyncHttpEvent.builder()
                .asyncContext(asyncContext)
                .response(resp)
                .build();
        //ThreadLocalContext.threadLocalIEvent.set(iEvent);
        userService.getAsyncUser(iEvent, 2, threadName, requestId);
        //userService.getAsyncUser(2, threadName, requestId);


    }


}
